﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_MasterData_Location : System.Web.UI.UserControl
{
    DBDataContext db;
    DatabaseHelper helper;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
            Utils.loadLocation(cbProvince, 0, 1);
    }
    private void getDataSearch()
    {
        try
        {
            string strName = Utils.KillChars(txtNameSearch.Text.Trim());
            DataTable dt = loadData(0, strName, this.rtpFromDateSearch.SelectedDate, this.rtpToDateSearch.SelectedDate);
            if (dt.Rows.Count > 0)
            {
                gvData.Height = 250;
                gvData.ClientSettings.Scrolling.AllowScroll = true;
                gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
                gvData.VirtualItemCount = Convert.ToInt32(dt.Rows.Count);
                gvData.DataSource = dt;
            }
            else
                gvData.DataSource = new DataTable();
            //gvData.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Vendor Page-getDataSearch:" + ex.Message.ToString());
        }
    }
    private DataTable loadData(int ID = 0, string strName = "", DateTime? dFromDate = null, DateTime? dToDate = null)
    {
        DataTable dt = new DataTable();
        try
        {
            if (dFromDate == null)
                dFromDate = DateTime.Parse("2014-01-01");
            if (dToDate == null)
                dToDate = DateTime.Parse("2099-01-01");
            db = new DBDataContext();
            var list1 = (from a in db.Locations
                         join b in db.Locations on  a.ParentID equals b.ID  into joined
                         where a.Status == 'A'
                                && (a.ID == ID || ID == 0)
                                && (a.LocationName.StartsWith(strName) || strName == "")
                                && (a.LastUpdatedDateTime <= dToDate && a.LastUpdatedDateTime >= dFromDate)
                         from b in joined.DefaultIfEmpty()
                         orderby a.LastUpdatedDateTime descending
                         select new
                         {
                             LocationID = a.ID,
                             LocationName = a.LocationName,
                             ProvinceName = b.LocationName,
                             ParentID = a.ParentID,
                             LastUpdatedBy = a.LastUpdatedBy,
                             LastUpdatedDateTime = string.Format("{0:dd/MM/yyyy}", a.LastUpdatedDateTime)
                         });
            //Xu ly RowID
            var list = list1.AsEnumerable().Select((b, index) => new
            {
                    LocationID = b.LocationID,
                    LocationName = b.LocationName,
                    ParentID = b.ParentID,
                    ProvinceName = b.ProvinceName,
                    LastUpdatedBy = b.LastUpdatedBy,
                    LastUpdatedDateTime = string.Format("{0:dd/MM/yyyy}", b.LastUpdatedDateTime),
                RowID = index + 1
            }).ToList();
            dt = list.ToDataTable();
            if (dt.Rows.Count > 0)
                div_TotalRows.InnerText = "Kết quả tìm kiếm: " + String.Format("{0:N0}", dt.Rows.Count);

            else
                div_TotalRows.InnerText = "Kết quả tìm kiếm: 0";
        }

        catch (Exception ex)
        {
            ControlUtil.LogError("Location Page-loadData:" + ex.Message.ToString());
            return null;
        }
        return dt;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                
                if (String.IsNullOrEmpty(txtName.Text.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập tên!");
                    txtName.Focus();
                    return;
                }
                db = new DBDataContext();
                if (ViewState["LocationID"] == null)
                {
                    Location obj = new Location();
                    obj.LocationName = Utils.KillChars(txtName.Text.Trim());
                    obj.Description = Utils.KillChars(txtName.Text.Trim());
                    obj.ParentID = Convert.ToInt32(cbProvince.SelectedValue.Trim());
                    obj.CreatedBy = Session["Username"].ToString();
                    obj.CreatedDateTime = DateTime.Now;
                    obj.LastUpdatedBy = Session["Username"].ToString();
                    obj.LastUpdatedDateTime = DateTime.Now;
                    obj.Status = 'A';
                    db.Insert<Location>(obj);
                    db.SubmitChanges();
                    ViewState["LocationID"] = obj.ID;
                }
                else
                {
                    Location obj = db.Locations.FirstOrDefault(x => x.ID == Convert.ToInt32(ViewState["LocationID"]));
                    obj.LocationName = Utils.KillChars(txtName.Text.Trim());
                    obj.Description = Utils.KillChars(txtName.Text.Trim());
                    obj.ParentID = Convert.ToInt32(cbProvince.SelectedValue.Trim());
                    obj.LastUpdatedBy = Session["Username"].ToString();
                    obj.LastUpdatedDateTime = DateTime.Now;
                    db.SubmitChanges();
                }
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Lưu thành công!");
            }
            catch (Exception ex)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Lưu không thành công, vui lòng kiểm tra dữ liệu!");
                ControlUtil.LogError("Location Page-Save:" + ex.Message);
            }
        }
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Location", false);
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                if (ViewState["LocationID"] != null)
                {
                    db = new DBDataContext();
                    Location obj = db.Locations.FirstOrDefault(x => x.ID == Convert.ToInt32(ViewState["LocationID"]));
                    obj.LastUpdatedBy = Session["Username"].ToString();
                    obj.LastUpdatedDateTime = DateTime.Now;
                    obj.Status = 'I';
                    db.SubmitChanges();
                    btnCancel.Enabled = false;
                    btnSave.Enabled = false;
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa thành công!");
                }
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("Location Page-btnCancel_Click:" + ex.Message.ToString());
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công. Vui lòng kiểm tra dữ liệu và thực hiện lại!");
            }
        }
    }
    protected void gvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        try
        {
            //Ham phan trang: Paging
            if (RadPageView3.Selected)
            {
                TabStrip1.SelectedIndex = 3;
                gvData.Height = 250;
                gvData.Visible = true;
                getDataSearch();
            }
            else
            {
                gvData.DataSource = new DataTable();
            }
        }
        catch (Exception ex)
        {

        }
    }
    protected void gvData_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                string commandName = e.CommandName;
                int ID = Convert.ToInt32(e.CommandArgument.ToString());//Lay ID 
                helper = new DatabaseHelper();


                if (commandName == "EditItem")
                {
                    try
                    {
                        RadPageView1.Selected = true;
                        TabStrip1.SelectedIndex = 0;
                        DataTable dt = loadData(ID);
                        if (dt.Rows.Count > 0)
                        {
                            //text.Text = dt.Rows[0]["VendorCode"].ToString();
                            txtName.Text = dt.Rows[0]["LocationName"].ToString();
                            cbProvince.SelectedValue = dt.Rows[0]["ParentID"].ToString();
                            //txtAddress.Text = dt.Rows[0]["Address"].ToString();
                            //txtPhoneNumber.Text = dt.Rows[0]["PhoneNumber"].ToString();
                            txtLastUpdatedBy.Text = dt.Rows[0]["LastUpdatedBy"].ToString();
                            txtLastUpdatedDateTime.Text = dt.Rows[0]["LastUpdatedDateTime"].ToString();
                            ViewState["LocationID"] = dt.Rows[0]["LocationID"].ToString();
                            btnSave.Enabled = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("Location Page-gvData_ItemCommand-EditItem:" + ex.Message);
                    }
                }
                //else if (commandName == "DeleteItem")
                //{
                //    try
                //    {
                //        delete(ID);
                //        JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa tin thành công!");
                //        gvData.Rebind();
                //    }
                //    catch (Exception ex)
                //    {
                //        ControlUtil.LogError("StockTransfer Page-gvData_ItemCommand-DeleteItem:" + ex.Message);
                //        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
                //    }
                //}
            }
            catch (Exception ex)
            {
                ControlUtil.LogError("Location Page-gvData_ItemCommand:" + ex.Message);
            }
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        getDataSearch();
        gvData.DataBind();
    }
    
}